import traceback
from urllib.parse import parse_qs
from channels.db import database_sync_to_async
from django.db import close_old_connections
from django.contrib.auth.models import AnonymousUser
from jwt import decode as jwt_decode
# from jwt import
from django.conf import settings
from account.models import UserModel

@database_sync_to_async
def get_user(user_id):
    try:
        return UserModel.objects.get(pk=user_id)
    except UserModel.DoesNotExist:
        return AnonymousUser()


class JWTAuthMiddlewareStack:

    def __init__(self, app):
        # Store the ASGI application we were passed
        self.app = app

    async def __call__(self, scope, receive, send):
        close_old_connections()  # 关闭旧的数据库连接
        jwd_tokan_list = parse_qs(scope["query_string"].decode('utf-8')).get('token')
        try:
            if jwd_tokan_list:
                jwd_tokan_str = jwd_tokan_list[0]
                payload = self.get_payload(jwd_tokan_str)
                scope['user'] = await get_user(payload['user_id'])
            else:
                scope['user'] = AnonymousUser()
        except Exception as e:
            traceback.print_exc()
        return await self.app(scope, receive, send)

    def get_payload(self, jwd_tokan_str):
        """
        return: {
            'user_id': '1',    # 用户名
            'exp': 1741507819,      # 过期时间：expiration
            'origIat': 1741421419   # 生成时间：original issued at
        }
        """
        payload = jwt_decode(
            jwd_tokan_str, key=settings.SECRET_KEY, algorithms=["HS256"]
        )
        return payload